const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentTab: 0,
        selectTime: false,

        room: {},
        store: {},

        times: {},
        selected: [],
        select: [],

        select_date: '',
        select_start: '',
        select_end: '',
        nums: 0,

        date_arr: [],
        date_start: '',
        date_end: '',
        date: '',
        user:{},
        canIUseGetUserProfile: false,
        id:0,
        zd_bg:'',
        unitIndex:0,
        seeDetails: true,
        zd_t:'',
        zd_price:0,
        check_mt:true,
        sf_price:0,
        deal_id:'',
        coupon_id:'',
        tg_coupon_id:'',
        coupon_type:'',
        TotalPrice:0,
        deposit:100,
        time: '12:01',
        spaces:'',
        arr:[
            {
          name:21,
          flag:true
        },{
          name:22,
          flag:true
        },{
          name:23,
          flag:true
        },
        {
          name:0,
          flag:true
        },{
          name:1,
          flag:true
        },{
          name:2,
          flag:true
        },
        {
          name:3,
          flag:false
        },{
          name:4,
          flag:false
        },{
          name:5,
          flag:true
        },
        {
          name:6,
          flag:true
        },{
          name:7,
          flag:true
        },{
          name:8,
          flag:true
        },  {
          name:9,
          flag:true
        },{
          name:10,
          flag:true
        },{
          name:11,
          flag:true
        },
        {
          name:12,
          flag:true
        },{
          name:13,
          flag:true
        },{
          name:14,
          flag:true
        },  {
          name:15,
          flag:true
        },{
          name:16,
          flag:true
        },{
          name:17,
          flag:true
        },
        {
          name:18,
          flag:true
        },{
          name:19,
          flag:true
        },{
          name:20,
          flag:true
        },
      ],
      totaltime:0,
      numes:'',
      nowstime:'',//现在的时间
      selecttime:'',//选择时间段
    //   预约时间段和不可预约时间段----------
    timePickerValue: { hour: 0, minute: 0, second: 0 }, // 时间选择器的值  
    timePickerDisabled: false, // 控制时间选择器的禁用状态  
    selectableTime: '09:00-17:00', // 可预约的时间范围  
     // tab_active:false
    // 第一种方法
    timeslot:[
        {name: '00:00', flag: false },
        { name: '01:00',flag: false },
        { name: '02:00',flag: false },
        { name: '03:00',flag: false },
        { name: '04:00',flag: true },
        { name: '05:00',flag: false },
        { name: '06:00',flag: false },
        { name: '07:00',flag: false },
        { name: '08:00',flag: true },
        { name: '09:00',flag: false },
        { name: '10:00',flag: false },
        { name: '11:00',flag: true },
        { name: '12:00',flag: false },
        { name: '13:00',flag: false },
        { name: '14:00',flag: false },
        { name: '15:00',flag: false },
        { name: '16:00',flag: false },
        { name: '17:00',flag: false },
        { name: '18:00',flag: false },
        { name: '19:00',flag: false },
        { name: '20:00',flag: false },
        { name: '21:00',flag: false },
        { name: '22:00',flag: false },
        { name: '23:00',flag: false },
        { name: '24:00',flag: false },
      ],
      timeRange: [
        { time: '09:00', isBooked: false },//false已预订，true没有预定
        { time: '10:00', isBooked: true },
        { time: '11:00', isBooked: false },
        { time: '12:00', isBooked: false },
        { time: '13:00', isBooked: true },
        { time: '14:00', isBooked: false },
        { time: '15:00', isBooked: false },
        { time: '16:00', isBooked: false },
        { time: '17:00', isBooked: true },
        { time: '18:00', isBooked: false }
      ],
      selectedTimeIndex: -1,
      shows:true,
      TimeIndex:'',
    },
        // 第一种方法
        onTimeTap(e) {
            const index = e.currentTarget.dataset.index;
            console.log(index,'index-------------')
            this.setData({
                TimeIndex:index,
              selectedTimeIndex: index
            });
          },
          onConfirm() {
            const selectedTime = this.data.timeRange[this.data.selectedTimeIndex].time;
            // 处理确认按钮点击事件
            console.log('Confirmed time: ' + selectedTime);
            // 关闭时间选择器
            this.closeTimePicker();
          },
          onCancel() {
              this.setData({
                shows:false
              })
            // 处理取消按钮点击事件
            // 关闭时间选择器
            this.closeTimePicker();
          },
          closeTimePicker() {
            // 关闭时间选择器的方法
          },


       //   预约时间段和不可预约时间段----------
    checkTime:function(){  
        const currentTime = new Date();  
        const startTime = new Date();  
        const endTime = new Date();  
        startTime.setHours(9); // 设置开始时间为9点  
        endTime.setHours(17); // 设置结束时间为17点  
        if (currentTime >= startTime && currentTime <= endTime) {  
          // 当前时间在可预约时间范围内，设置时间选择器为可用状态  
          this.setData({ timePickerDisabled: false });  
        } else {  
          // 当前时间不在可预约时间范围内，设置时间选择器为禁用状态  
          this.setData({ timePickerDisabled: true });  
        }  
      },
  goCupon:function(){
    wx.navigateTo({
        url: '/pages/coupon/coupon',
    })
},
    gotuanCupon:function(e){
    var deal_id = e.currentTarget.dataset.id;
    wx.navigateTo({
        url: '/pages/tg_coupon/tg_coupon?deal_id='+deal_id,
    })
    },
    book: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/book/book?id=' + id
        })
    },
    unsettled: function () {
        // 上面部分
        if (this.data.numes=='') {
            wx.showToast({
                title: '预定时间时间至少1小时起步',
                icon: 'none'
            });
            return false;
        }else if(this.data.numes){
            console.log(this.data.numes,'this.data.numes')
            // var alltimes=
            wx.showToast({
                title: '预定时间'+this.data.room.start_dtime+'小时起',
                icon: 'none'
            });
        }

        // 下面部分
        var nums = this.data.nums;
        console.log(this.data.room.start_dtime,nums,'this.data.room.start_dtime,nums-------')
        if (nums < this.data.room.start_dtime) {
            wx.showToast({
                title: nums ? '预定时间'+this.data.room.start_dtime+'小时起' : '请选择预定时间',
                icon: 'none'
            });
            return false;
        }
        var room_id = this.data.id,
            date = this.data.select_date,
            timeslot = [],
            times = this.data.times,
            start = this.data.select_start,
            end = this.data.select_end;
        for (var i in times) {
            if (times[i].select) {
                timeslot.push(times[i].time);
            }
        }
console.log(timeslot,'timeslot---------------')
        app.ajax({
            url: '/api/user/addOrder',
            data: {
                room_id: room_id,
                date: date,
                timeslot: timeslot.join(','),
                nums: nums
                
            },
            success: res => {
                if (res.code == 1) {
                    console.log(res,'res----------code')
                    wx.navigateTo({
                        url: '/pages/unsettled/unsettled?order_id=' + res.data.id+"&TotalPrice="+ this.data.TotalPrice+"&deposit="+  this.data.deposit
                    })
                }else if (res.code == 301) {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });

                    //倒计时延迟2秒才行
                    wx.navigateTo({
                        url: '/pages/account_chongzhi/account_chongzhi'
                    })

                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            }
        }, 1);
    },
    stopBubb: function () {
        return false
    },
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: this.data.store.mobile,
            success: function () {},
        })
    },
    select_time: function () {
        this.setData({
            selectTime: true
        });
    },
    close_time: function () {
        this.setData({
            selectTime: false
        });
    },
    confirm_time: function () {
      console.log(Number(this.data.room.price) * this.data.nums,'---------')
        this.setData({
            selectTime: false,
            zd_t: this.data.zd_t=this.data.nums,
            TotalPrice:  Number(this.data.room.price) * this.data.nums+this.data.deposit,
            sf_price:Number(this.data.room.price) * this.data.nums+this.data.deposit,
        });
    },

    // 滑动切换tab
    bindChange: function (e) {
        var that = this;
        that.setData({
            currentTab: e.detail.current
        });
    },
    slidertimes2:function(){
        　console.log(this.data.numes ,'this.data.numes ------')
        // 
        var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
        Largetime= Largetime.replace('ms','\t')
        　var date = new Date(Largetime);
        　　var timestamp = date.getTime();
            timestamp=timestamp+this.data.numes*3600000
            this.sliderchange(timestamp)
    },

    // 点击tab切换
    swichNav: function (e) {
        if(e.currentTarget.dataset.date!==this.data.nowstime){
            this.setData({
                selecttime: 0,
            })
        }else if(e.currentTarget.dataset.date==this.data.nowstime){
         this.bindDatePackage()
        }
        // 下面
        var date = e.currentTarget.dataset.date;
        if (this.data.select_date == date) {
            return false;
        } else {
            this.setData({
                select_date: date
            });
            this.slidertimes2();//更新
            this.getSelectedTimes();//接口调用
            
        }
    },
    bindDatePackage(){
        var now = new Date();
        var hours = now.getHours()+':';
        var minutes = now.getMinutes();
        this.data.time= hours+minutes
            this.setData({
                selecttime: this.data.time,
                time: this.data.time
            })
    },
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        var date = e.detail.value;
        this.setData({
            date: date,
            select_date: date
        })
        this.getSelectedTimes();
        this.slidertimes2()
    },
    selectTime: function (e) {
        // console.log(e,'selectTime--------')
        var times = this.data.times,
            index = parseInt(e.currentTarget.dataset.index),
            time = e.currentTarget.dataset.time,
            select_start = this.data.select_start,
            select_end = this.data.select_end;
            console.log( this.data,'selectTime--------')
            // times[index].disabled=false
        if (times[index].disabled) {
            // console.log(e,'selectTime--------')
            return false;
        }
        if (select_start !== '' && select_end !== '') {
            for (var i in times) {
                times[i].select = false;
            }
            times[index].select = true;
            this.setData({
                select_start: index,
                select_end: '',
                nums: 0,
                times: times
            })
        } else if (select_start !== '') {
            if (select_start == index) {
                times[index].select = false;
                this.setData({
                    select_start: '',
                    times: times
                });
                return false;
            } else if (index > select_start) {
                select_end = index;
            } else {
                select_end = select_start;
                select_start = index;
            }
            var error = false,
                nums = 0;
            for (var i in times) {
                times[i].select = false;
                if (i >= select_start && i <= select_end) {
                    if (times[i].disabled) {
                        error = true;
                    }
                    times[i].select = true;
                    nums += 0.5;
                }
            }
            if (nums > 0) nums -= 0.5;
            if (error) {
                wx.showToast({
                    title: '存在不可选项',
                    icon: 'none'
                });
                return false;
            }
            this.setData({
                select_start: select_start,
                select_end: select_end,
                times: times,
                nums: nums
            })
        } else {
            times[index].select = true;
            this.setData({
                times: times,
                select_start: index
            })
        }
    },
    getTimes: function (selected) {
        var times = {},
            open = this.data.store.open,
            open_key = this.getTimeKey(open),
            close = this.data.store.close,
            close_key = this.getTimeKey(close);
        selected = selected || [];

        for (var i = 0; i < 48; i++) {
            var h = parseInt(i / 2),
                m = 30 * (i % 2),
                key = h * 100 + m,
                time = ('0' + h).slice(-2) + ':' + ('0' + m).slice(-2),
                disabled = false;
            if (selected.indexOf(time) > -1) disabled = true;
            if (open_key != close_key && (key < open_key || key > close_key)) disabled = true;
            times[key] = {
                key: key,
                time: time,
                disabled: disabled
            };
        }
        
        this.setData({
            times: times,
            nums: 0,
            select_start: '',
            select_end: ''
        })
    },
    getTimeKey: function (time) {
        if (!time) return 0;
        var arr = time.split(':');
        return arr[0] * 100 + arr[1] * 1;
    },
    bindTimeChange: function(e) {
   console.log('触发了选中的时间',e)

        this.setData({
          time: e.detail.value
        })
        this.slidertimes2()
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    //   预约时间段和不可预约时间段----------  
    this.checkTime();

    // 获取当前的年，月，日
    var now = new Date();
    var year = now.getFullYear()+ '-';
    var month = now.getMonth()+1+ '-';
    var date = now.getDate();
    var hours = now.getHours()+':';
    var minutes = (now.getMinutes() < 10 ? '0' + (now.getMinutes()) : now.getMinutes()) ;
    // var minutes = now.getMinutes();
    // var seconds = now.getSeconds();
    this.data.nowstime=year + month + date  
    this.data.time= hours+minutes
    // 下面
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true,
                nowstime:this.data.nowstime,
                time: this.data.time,
                selecttime:this.data.time
            })
        }
        var that = this
        var sence_id=decodeURIComponent(options.scene).split('=')[1]
        wx.getSystemInfo({
            success: function (res) {
                
                that.setData({
                    clientHeight: res.windowHeight - 176
                });
            }
        })

        var id = options.id || sence_id,
            stores = wx.getStorageSync('stores'),
            store, room,room_img=[],details=[];
            this.data.id = id
        for (var i in stores) {
            for (var j in stores[i].rooms) {
                if (stores[i].rooms[j].id == id) {
                    room = stores[i].rooms[j];
                    store = stores[i];

                    details.push({
                      id: stores[i].id,
                      address: stores[i].address,
                      lat: stores[i].lat,
                      lon: stores[i].lon,
                      name: stores[i].name
                    });
                }
            }
        }
        room_img.push(room.image,room.image1,room.image2)
        var box_time=[],box_t  = store.zd_time
        this.data.zd_t = box_t[0];
        this.data.zd_price = room.price
        this.data.sf_price = room.price*box_t[0]
        // this.data.sf_price =  Number(this.data.TotalPrice)
        for (var i in box_t) {
          box_time[i] = [{'t':box_t[i],'c':box_t[i]+'小时'}]
        }
         box_time = [].concat.apply([], box_time);
        if (!store || !room) {
            wx.showToast({
                title: '查看内容不存在',
                icon: 'none'
            });
            setTimeout(function () {
                wx.navigateBack({
                    delta: 1
                })
            }, 1500);
        }
        this.setData({
            id: id,
            room: room,
            store: store,
            room_img:room_img,
            details:details,
            box_time:box_time,
            sf_price:room.price*box_t[0],
            zd_t:this.data.zd_t
        });

        var date_arr = [];
        for (var i = 0; i < 3; i++) {
            var now = new Date().getTime() + i * 86400000;
            date_arr.push(this.getDate(now));
        }
        console.log(date_arr);
        var start_date = this.getDate(Date.now() + 86400000 * 3),
            end_date = this.getDate(Date.now() + 86400000 * 30);
        this.setData({
            date_arr: date_arr,
            date_start: start_date.date,
            date_end: end_date.date,
            select_date: date_arr[0].date
        });

        this.getSelectedTimes();
        this.slidertimes2()
    },
    //自定选择时间盒子
    zd_time:function(e){
      this.data.zd_t = e.target.dataset.t;
      this.data.sf_price = this.data.zd_t*this.data.zd_price;
      let index = e.target.dataset.index;
      this.setData({
        unitIndex: index,
        zd_t:this.data.zd_t,
        sf_price: this.data.sf_price
      })
    },
    see_details: function () {
      var seeDetails = this.data.seeDetails
      seeDetails = !seeDetails
      this.setData({
        seeDetails: seeDetails
      })
    },

    listenerBtnGetLocation:function(e){
      var lat = e.currentTarget.dataset.lat;
      var tel = e.currentTarget.dataset.lon;
      var name = e.currentTarget.dataset.name;
      var address = e.currentTarget.dataset.address;
      console.log(lat)
      console.log(tel)
      wx.getLocation({
        //定位类型 wgs84, gcj02
        type: 'gcj02',
        success: function(res) {
          console.log(res)
          //return false
          wx.openLocation({
            //当前经纬度
            latitude: res.latitude,
            longitude: res.longitude,
            //缩放级别默认28
            scale: 28,
            //位置名
            name: name,
            //详细地址
            address: address,
            // //成功打印信息
            // success: function(res) {
            //   console.log(res)
            // },
            // //失败打印信息
            // fail: function(err) {
            //   console.log(err)
            // },
            // //完成打印信息
            // complete: function(info){
            //   console.log(info)
            // },
          })
   
        },
        fail: function(err) {
          console.log(err)
        },
        complete: function(info) {
          console.log(info)
        },
      })
      
    },
    getDate: function (now) {
        var date = new Date(now),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            w = date.getDay(),
            d = date.getDate(),
            weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        m = ('0' + m).slice(-2);
        d = ('0' + d).slice(-2);
        return {
            week: weeks[w],
            date: y + '-' + m + '-' + d,
            name: m + '月' + d + '日'
        };
    },
    getSelectedTimes: function () {
        app.ajax({
            url: '/api/index/roomTimes',
            data: {
                id: this.data.id,
                date: this.data.select_date
            },
            success: res => {
                if (res.code == 1) {
                    this.getTimes(res.data);
                }
            }
        }, 1);
    },
    userinfo: function() {
        app.ajax({
            url: '/api/user/userinfo',
            success: res => {
                if (res.code == 1) {
                    wx.setStorageSync('user', res.data);
                    this.setData({
                        user: res.data
                    })
                }
            }
        })
    },
    getScanStores:function(){
            app.ajax({
                url: '/api/index/stores',
                data: {},
                success: res => {
                    if (res.code == 1) {
                        wx.setStorageSync('stores', res.data);
                        var stores = res.data
                        var id = this.data.id,
                        stores = wx.getStorageSync('stores'),
                        store, room;
                    for (var i in stores) {
                        for (var j in stores[i].rooms) {
                            if (stores[i].rooms[j].id == id) {
                                room = stores[i].rooms[j];
                                store = stores[i];
                            }
                        }
                    }
                    this.setData({
                        id: id,
                        room: room,
                        store: store
                    });


                    } else {
                        wx.removeStorageSync('stores');
                        this.setData({
                            details:[]
                        })
                    }
                }
            })
    },
    login: function(e) {
        console.log(e);

        console.log(this.data.canIUseGetUserProfile);
        if (this.data.canIUseGetUserProfile){
            console.log('getUserProfile')
            wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                    console.log(res)
                    if (!res.userInfo) {
                        wx.showToast({
                            title: '未获取到用户信息',
                            icon: 'none'
                        });
                        return;
                    }
                    wx.setStorageSync('userinfo', res.userInfo);
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            })
        } else {
            if (!e.detail.userInfo) {
                wx.showToast({
                    title: '未获取到用户信息',
                    icon: 'none'
                });
                return;
            }
            wx.setStorageSync('userinfo', e.detail.userInfo);
            wx.navigateTo({
                url: '/pages/login/login'
            })
        }
    },
    sliderchange:function(e){
        var date = new Date(e); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) ;
        this.data.totaltime=Y + M + D + h + m 
        // var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
        this.setData({
            totaltime: this.data.totaltime
        })
    },
    slider3change:function(e){
        this.setData({
            numes: e.detail.value
        })
        var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
        Largetime= Largetime.replace('ms','\t')
    　　var date = new Date(Largetime);
    　　var timestamp = date.getTime();
        timestamp=timestamp+e.detail.value*3600000
        this.sliderchange(timestamp)
       
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.userinfo();
        var stores = wx.getStorageSync('stores')
        if(stores == null || stores == ''){
            this.getScanStores()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
 
    order_pay: function () {
        var room_id = this.data.id;
        var zd_t = this.data.zd_t;

        var post_data = {
          room_id: room_id,
          zd_t:zd_t,
          deal_id:this.data.deal_id,
          coupon_type:this.data.coupon_type,
          coupon_id:this.data.coupon_id,
          tg_coupon_id:this.data.tg_coupon_id
      }
        wx.showModal({
            title: '确认订单？',
            //content: '这是一个模态弹窗',
            success (response) {
              if (response.confirm) {
                console.log('用户点击确定')
                app.ajax({
                    url: '/api/user/addOrder',
                    data:post_data,
                    success: res => {
                        if (res.code == 1) {
                            wx.navigateTo({
                                url: '/pages/opening_code/opening_code?order_id=' + res.data.id
                            })
                        // 余额不足跳转到充值页面
                        } else if (res.code == 301) {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });

                            //倒计时延迟2秒才行
                            setTimeout(()=>{
                                wx.navigateTo({
                                    url: '/pages/account_chongzhi/account_chongzhi'
                                })
                            },1000)

                        }else if (res.code == 400) {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });
                            //倒计时延迟2秒才行
                            setTimeout(()=>{
                                wx.navigateTo({
                                    delta: 1
                                })
                            },3000)
                        } else if (res.data.code == -2) {
                            wx.showToast({
                                title: '未登录或登陆已失效',
                                icon: 'none'
                            });
                            wx.navigateTo({
                                url: '/pages/login/login'
                            })
                            return false;
                        }
                        else {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });
                        }
                    }
                }, 1);

              } else if (response.cancel) {
                console.log('用户点击取消')
              }
            }
          })

    }
})

